package jnpf.zcasset.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.xuyanwu.spring.file.storage.FileInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.DownloadVO;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.config.ConfigValueUtil;
import jnpf.exception.DataException;
import jnpf.permission.entity.UserEntity;
import jnpf.util.*;
import jnpf.zcasset.entity.ZcCustomerEntity;
import jnpf.zcasset.model.zccustomer.ZcCustomerForm;
import jnpf.zcasset.model.zccustomer.ZcCustomerInfoVO;
import jnpf.zcasset.model.zccustomer.ZcCustomerListVO;
import jnpf.zcasset.model.zccustomer.ZcCustomerPagination;
import jnpf.zcasset.service.ZcCustomerService;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * zc_customer
 *
 * @版本： V3.2.0
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期：
 */
@Slf4j
@RestController
@Api(tags = "zc_customer", value = "zc")
@RequestMapping("/api/zc/zcCustomer")
public class ZcCustomerController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private ConfigValueUtil configValueUtil;

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private ZcCustomerService zc_customerService;

    /**
     * 列表
     *
     * @param zc_customerPagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZcCustomerPagination zc_customerPagination) throws IOException {
        List<ZcCustomerEntity> list = zc_customerService.getList(zc_customerPagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<ZcCustomerListVO> listVO = JsonUtil.getJsonToList(list, ZcCustomerListVO.class);
        for (ZcCustomerListVO zc_customerVO : listVO) {
            zc_customerVO.setCustomerName_name(zc_customerVO.getCustomerName());

            zc_customerVO.setProject_name(zc_customerVO.getProject());

            zc_customerVO.setCustomerSource_name(generaterSwapUtil.getDicName(zc_customerVO.getCustomerSource(), "610927544136368837"));

            zc_customerVO.setCustomerType_name(generaterSwapUtil.getDicName(zc_customerVO.getCustomerType(), "610927785631810245"));

            zc_customerVO.setCustomerNature_name(generaterSwapUtil.getDicName(zc_customerVO.getCustomerNature(), "610927785631810245"));

            zc_customerVO.setIndustry_name(generaterSwapUtil.getDicName(zc_customerVO.getIndustry(), "610927980662751941"));

            zc_customerVO.setCustomerCode_name(zc_customerVO.getCustomerCode());

            zc_customerVO.setDetailedAddress_name(zc_customerVO.getDetailedAddress());

            zc_customerVO.setRemark_name(zc_customerVO.getRemark());

            zc_customerVO.setContactName_name(zc_customerVO.getContactName());

            zc_customerVO.setContactNumber_name(zc_customerVO.getContactNumber());

            zc_customerVO.setContactEmail_name(zc_customerVO.getContactEmail());

            //子表数据转换
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zc_customerPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param zc_customerForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid ZcCustomerForm zc_customerForm) throws DataException {
        boolean b = zc_customerService.checkForm(zc_customerForm, 0);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        ZcCustomerEntity entity = JsonUtil.getJsonToBean(zc_customerForm, ZcCustomerEntity.class);
        entity.setId(mainId);
        entity.setCreatorUserId(userProvider.get().getUserId());
        zc_customerService.save(entity);
        return ActionResult.success("创建成功");
    }

    /**
     * 模板下载
     *
     * @return
     */
    @ApiOperation("模板下载")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO> TemplateDownload() {
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = DownloadVO.builder().build();
        try {
            vo.setName("职员信息.xlsx");
            vo.setUrl(UploaderUtil.uploaderFile("/api/Common/DownloadModel?encryption=", userInfo.getId() + "#" + "职员信息.xlsx" + "#" + "Temporary"));
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
        }
        return ActionResult.success(vo);
    }

    /**
     * 导出Excel
     *
     * @return
     */
    @ApiOperation("导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody ZcCustomerPagination zc_customerPagination) throws IOException {
        if (StringUtil.isEmpty(zc_customerPagination.getSelectKey())) {
            return ActionResult.fail("请选择导出字段");
        }
        List<ZcCustomerEntity> list = zc_customerService.getTypeList(zc_customerPagination, zc_customerPagination.getDataType());
        //处理id字段转名称，若无需转或者为空可删除

        List<ZcCustomerListVO> listVO = JsonUtil.getJsonToList(list, ZcCustomerListVO.class);
        for (ZcCustomerListVO zc_customerVO : listVO) {
            zc_customerVO.setCustomerName_name(zc_customerVO.getCustomerName());

            zc_customerVO.setProject_name(zc_customerVO.getProject());

            zc_customerVO.setCustomerSource_name(generaterSwapUtil.getDicName(zc_customerVO.getCustomerSource(), "610927544136368837"));

            zc_customerVO.setCustomerType_name(generaterSwapUtil.getDicName(zc_customerVO.getCustomerType(), "610927785631810245"));

            zc_customerVO.setCustomerNature_name(generaterSwapUtil.getDicName(zc_customerVO.getCustomerNature(), "610927785631810245"));

            zc_customerVO.setIndustry_name(generaterSwapUtil.getDicName(zc_customerVO.getIndustry(), "610927980662751941"));

            zc_customerVO.setCustomerCode_name(zc_customerVO.getCustomerCode());

            zc_customerVO.setDetailedAddress_name(zc_customerVO.getDetailedAddress());

            zc_customerVO.setRemark_name(zc_customerVO.getRemark());

            zc_customerVO.setContactName_name(zc_customerVO.getContactName());

            zc_customerVO.setContactNumber_name(zc_customerVO.getContactNumber());

            zc_customerVO.setContactEmail_name(zc_customerVO.getContactEmail());

            //子表数据转换
        }

        //转换为map输出
        List<Map<String, Object>> mapList = JsonUtil.getJsonToListMap(JsonUtil.getObjectToStringDateFormat(listVO, "yyyy-MM-dd HH:mm:ss"));
        mapList.stream().forEach(map -> {
            Map<String, Object> map2 = new HashMap<>();
            map.putAll(map2);
        });
        String[] keys = !StringUtil.isEmpty(zc_customerPagination.getSelectKey()) ? zc_customerPagination.getSelectKey().split(",") : new String[0];
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = this.creatModelExcel(configValueUtil.getTemporaryFilePath(), mapList, keys, userInfo);
        return ActionResult.success(vo);
    }

    //导出表格
    public DownloadVO creatModelExcel(String path, List<Map<String, Object>> list, String[] keys, UserInfo userInfo) {
        DownloadVO vo = DownloadVO.builder().build();
        List<ExcelExportEntity> entitys = new ArrayList<>();
        if (keys.length > 0) {
            for (String key : keys) {
                switch (key) {
                    case "customerName":
                        entitys.add(new ExcelExportEntity("客户名称", "customerName_name"));
                        break;
                    case "project":
                        entitys.add(new ExcelExportEntity("项目", "project_name"));
                        break;
                    case "customerSource":
                        entitys.add(new ExcelExportEntity("来源", "customerSource_name"));
                        break;
                    case "customerType":
                        entitys.add(new ExcelExportEntity("客户类型", "customerType_name"));
                        break;
                    case "customerNature":
                        entitys.add(new ExcelExportEntity("客户性质", "customerNature_name"));
                        break;
                    case "industry":
                        entitys.add(new ExcelExportEntity("所属行业", "industry_name"));
                        break;
                    case "customerCode":
                        entitys.add(new ExcelExportEntity("社会信用代码/身份证", "customerCode_name"));
                        break;
                    case "detailedAddress":
                        entitys.add(new ExcelExportEntity("详细地址", "detailedAddress_name"));
                        break;
                    case "remark":
                        entitys.add(new ExcelExportEntity("备注", "remark_name"));
                        break;
                    case "contactName":
                        entitys.add(new ExcelExportEntity("联系人姓名", "contactName_name"));
                        break;
                    case "contactNumber":
                        entitys.add(new ExcelExportEntity("联系人电话", "contactNumber_name"));
                        break;
                    case "contactEmail":
                        entitys.add(new ExcelExportEntity("联系人邮箱", "contactEmail_name"));
                        break;
                    default:
                        break;

                }
            }
            List<String> keylist = new ArrayList<>();
            for (String key : keys) {
                keylist.add(key);
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size() > 0) {
                if (list.size() == 0) {
                    list.add(new HashMap<>());
                }
                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
            }
            String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";

            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }

    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<ZcCustomerInfoVO> info(@PathVariable("id") String id) {
        ZcCustomerEntity entity = zc_customerService.getInfo(id);
        ZcCustomerInfoVO vo = JsonUtil.getJsonToBean(entity, ZcCustomerInfoVO.class);

        //子表
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<ZcCustomerInfoVO> detailInfo(@PathVariable("id") String id) {
        ZcCustomerEntity entity = zc_customerService.getInfo(id);
        ZcCustomerInfoVO vo = JsonUtil.getJsonToBean(entity, ZcCustomerInfoVO.class);

        //子表数据转换

        //附表数据转换

//添加到详情表单对象中
        vo.setCustomerName(vo.getCustomerName());

        vo.setProject(vo.getProject());

        vo.setCustomerSource(generaterSwapUtil.getDicName(vo.getCustomerSource(), "610927544136368837"));

        vo.setCustomerType(generaterSwapUtil.getDicName(vo.getCustomerType(), "610927785631810245"));

        vo.setCustomerNature(generaterSwapUtil.getDicName(vo.getCustomerNature(), "610927785631810245"));

        vo.setIndustry(generaterSwapUtil.getDicName(vo.getIndustry(), "610927980662751941"));

        vo.setCustomerCode(vo.getCustomerCode());

        vo.setDetailedAddress(vo.getDetailedAddress());

        vo.setRemark(vo.getRemark());

        vo.setContactName(vo.getContactName());

        vo.setContactNumber(vo.getContactNumber());

        vo.setContactEmail(vo.getContactEmail());
        return ActionResult.success(vo);
    }

    /**
     * 更新
     *
     * @param id
     * @param zc_customerForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ZcCustomerForm zc_customerForm) throws DataException {
        boolean b = zc_customerService.checkForm(zc_customerForm, 1);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        UserInfo userInfo = userProvider.get();
        ZcCustomerEntity entity = zc_customerService.getInfo(id);
        if (entity != null) {
            ZcCustomerEntity subentity = JsonUtil.getJsonToBean(zc_customerForm, ZcCustomerEntity.class);
            subentity.setLastModifyUserId(userProvider.get().getUserId());
            boolean b1 = zc_customerService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZcCustomerEntity entity = zc_customerService.getInfo(id);
        if (entity != null) {
            zc_customerService.delete(entity);

        }
        return ActionResult.success("删除成功");
    }
}
